$(function() {
	// 获取到cookie
	var cookieName = $.cookie('username')
	var cookieImg = $.cookie('img')
	console.log($.cookie('img'))
	if(cookieImg) {
		// onerror当文件加载失败时会触发这个事件
		var header = '<img src="' + cookieImg + '" onerror="this.src=\'images/user.png\'">'
		$('#user').empty().html(header + cookieName)
	}
	// 退出删除cookie
	$('.dropdown-menu li').last().click(function() {
		$.removeCookie('username')
		$.removeCookie('img')
		$.get('/back', function(data) {
			console.log(data)
			if(data.code == 'success') {
				location.href = '/'
			}
		})
	})
	$('#user').click(function() {
		if(!cookieName) {
			$(this).removeAttr('data-toggle')
			location.href = '/sign'
		}
	})
	function checkNumber() {
		var $val = $('textarea').val().length
		$('textarea').next().text(140 - $val + '/140')
	}
	var timer
	$('textarea').focus(function() {
		timer = setInterval(checkNumber, 20)
	})
	$('textarea').blur(function() {
		clearInterval(timer)
	})
	$('.modal-close').click(function() {
		$('.modal').modal('hide')
	})
	//发起请求
	console.log($.cookie())
	$('form').submit(function(ev) {
		ev.preventDefault()
		var id = $.cookie('userId')
		var asId = $.cookie('askId')
		var data = $(this).serialize() + "&userId=" + id + "&askId=" + asId
		console.log(data)

		$.post('/answer', data).done(function(data) {
			if(data.code == 'success') {
				setTimeout(function() {
					location.href = '/'
				}, 200);
			}
		})
	})
})